package com.iamk.feature;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

import com.iamk.util.GetData;

public class FColorLabelMe {
	final static int NUMBER_SEG = 3;
	int height;
	int width;
	BufferedImage img;
	public Image imgSeg;
	public int[][] mask;
	ArrayList<int[][]> listMask;
	String fileMask;
	int maxRegion;
	int minPixcel;
	ArrayList<float[]> result = new ArrayList<float[]>();

	public FColorLabelMe(BufferedImage img, String fileMask, int minPixel) {
		// TODO Auto-generated constructor stub
		this.img = img;
		this.fileMask = fileMask;
		this.minPixcel = minPixel;
	}

	private void init() {
		// TODO Auto-generated method stub
		height = img.getHeight();
		width = img.getWidth();
		int[][] temp = new int[height][width];
		if (mask == null) {
			mask = GetData.readMaskFile(fileMask);
		}
		for (int i = 0; i < mask.length; i++) {
			for (int j = 0; j < mask[0].length; j++) {
				temp[j][i % width] = mask[i][j];
			}
			// matrix
			if ((i + 1) % width == 0) {
				listMask.add(temp.clone());
			}
		}
	}

	public ArrayList<float[]> extract() {
		int[][] temp;
		float[] hsvPixel = new float[3];
		init();
		Region[] regions = new Region[listMask.size()];
		Color pixelColor = null;
		for (int i = 0; i < regions.length; i++) {
			regions[i] = new Region();
		}
		for (int x = 0; x < height; x++) {
			for (int y = 0; y < width; y++) {
				pixelColor = new Color(img.getRGB(y, x));
				Color.RGBtoHSB(pixelColor.getRed(), pixelColor.getGreen(),
						pixelColor.getBlue(), hsvPixel);
				for (int k = 0; k < listMask.size(); k++) {
					temp = listMask.get(k);
					if (temp[x][y] > 0) {
						regions[k].pixels.add(hsvPixel.clone());
						if (regions[k].label == 0) {
							regions[k].label = temp[x][y];
						}
					}
				}
			}
		}
		// imges mask region
		for (int i = 0; i < regions.length; i++) {
			if (regions[i].pixels.size() > minPixcel) {
				regions[i].extract();
				result.add(regions[i].featuresLabel);
			}
		}
		return result;
	}
	public ArrayList<float[]> getResult() {
		extract();
		return result;
	}
}
